﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WindowsFormsApplication1.test;
using System.Media;

namespace WindowsFormsApplication1
{
    public partial class Portal : Form
    {
        #region Variables

        /// <summary>
        /// The timer: (for handling see TimerEvent).
        /// </summary>
        private Timer MainTimer = new Timer();

        /// <summary>
        /// Refference to the (mother) Login Form.
        /// </summary>
        private Login log;

        /// <summary>
        /// The webservice connection.
        /// </summary>
        Service1 webservice;

        /// <summary>
        /// UserName.
        /// </summary>
        string user = "";

        string invitee = "";

        /// <summary>
        /// Array of strings which contains all chatmessages.
        /// </summary>
        string[] strMess;

        /// <summary>
        /// Index of the chat.
        /// </summary>
        public int index = 0;

        /// <summary>
        /// the index of the invitee.
        /// </summary>
        private int InvIndex;

        /// <summary>
        /// List of blocked usernames.
        /// </summary>
        private List<string> BlockList = new List<string>();

        /// <summary>
        /// Random number generator for finding a random player
        /// </summary>
        Random n = new Random();

        /// <summary>
        /// boolean which checks if the portal is inviting.
        /// </summary>
        private bool inviting = false;

        /// <summary>
        /// boolean that stops repetetive messagebox pop-ups.
        /// </summary>
        private bool invReceived = false;

        /// <summary>
        /// bool that when true will make the portal closable.
        /// </summary>
        private bool StartGame = false;

        /// <summary>
        /// Boolean to check if the client needs to check for chat.
        /// </summary>
        private bool online = true;

        private bool sndRunning = false;

        /// <summary>
        /// size of the game.
        /// </summary>
        private int SizeG = 0;


       
        
        #endregion
        #region Methods

        /// <summary>
        /// The portal constructor, creates an instance of webservice, initialises the timer, creates the link to the login and makes sure the index and username are right.
        /// </summary>
        public Portal(Login login, string name)
        {
            InitializeComponent();
            webservice = new Service1();
            MainTimer.Interval = 100;
            MainTimer.Tick += TimerEvent;
            MainTimer.Start(); 
            log = login;
            user = name;
            index = webservice.Index();
            sndRunning = true;
            Login.sound.PlayLooping();
        }

        /// <summary>
        /// the timer event, adds messages to the chatlist and changes the list of online people.
        /// </summary>
        private void TimerEvent(Object myObject, EventArgs myEventArgs)
        {
            if (soundCheck.Checked && !sndRunning)
            {
                Login.SoundOn = true;
                Login.sound.PlayLooping();
                sndRunning = true;
            }
            else if (!soundCheck.Checked && sndRunning)
            {
                Login.SoundOn = false;
                Login.sound.Stop();
                sndRunning = false;
            }
            if (inviting == true)
            {
                int temp = webservice.InvResponse(user);
                if (temp == 1)
                {
                    if (webservice.GetGameIP() == "OFFLINE")
                    {
                        MessageBox.Show("The server is offline, please try again later", "Report");
                        inviting = false;
                    }
                    else
                    {
                        online = false;
                        StartGame = true;
                        webservice.Logout(user);
                        log.StartGame(SizeG, user, invitee);
                        this.Visible = false;
                        this.Close();
                    }
                }
                else if (temp == 2)
                {
                    MessageBox.Show("Your invitation has been declined.");
                    inviting = false;
                }
            }
            else
            {
                CheckInvitation();
            }
            if (online)
            {
                strMess = webservice.ReceiveMessage(index);
                index = (index + strMess.Length) % 5;
                for (int i = 0; i < strMess.Length; i++)
                {
                    ChatList.Items.Add(strMess[i]);
                }
                strMess = webservice.GetOnChatters(user);
                for (int i = 0; i < strMess.Length; i++)
                {
                    if (!PlayerList.Items.Contains(strMess[i]))
                    {
                        PlayerList.Items.Add(strMess[i]);
                    }
                }
                strMess = webservice.GetOffChatters(user);
                for (int i = 0; i < strMess.Length; i++)
                {
                    if (PlayerList.Items.Count > 0 && PlayerList.Items.Contains(strMess[i]))
                    {
                        PlayerList.Items.Remove(strMess[i]);
                    }
                }
            }
        }

        /// <summary>
        /// See if there are invitations for this client.
        /// </summary>
        private void CheckInvitation()
        {
            if (invReceived == false)
            {
                string[] temp = webservice.CheckInvitation(user);
                string size;
                if (temp[1] == "0")
                {
                    size = "small";
                }
                else if (temp[1] == "1")
                {
                    size = "medium";
                }
                else
                {
                    size = "big";
                }
                if (temp[0] != "")
                {
                    bool temper = false;
                    for (int i = 0; i < BlockList.Count; i++)
                    {
                        if (temp[0] == BlockList[i])
                        {
                            temper = true;
                            break;
                        }
                    }
                    if (temper == false)
                    {
                        invReceived = true;
                        DialogResult invite = MessageBox.Show((temp[0] + " invites you for a " + size + " game of battleship"), "Invitation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (invite == DialogResult.Yes)
                        {
                            webservice.SendResponse(user, true);
                            if (webservice.GetGameIP() == "OFFLINE")
                            {
                                MessageBox.Show("The server is offline, please try again later", "Report");
                                invReceived = false;
                            }
                            else
                            {
                                online = false;
                                StartGame = true;
                                webservice.Logout(user);
                                log.StartGame(Convert.ToInt32(temp[1]), temp[0], user);
                                this.Close();
                            }
                        }
                        else
                        {
                            webservice.SendResponse(user, false);
                            invReceived = false;
                        }
                    }
                    else
                    {
                        webservice.SendResponse(user, false);
                        invReceived = false;
                    }
                }
            }
        }

        #endregion
        #region User Interface

        /// <summary>
        /// The logout Button implementation.
        /// </summary>
        private void logoutBtn_Click(object sender, EventArgs e)
        {
            DialogResult dlgResult = MessageBox.Show("Are you sure you want to quit?", "Continue?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dlgResult == DialogResult.Yes)
            {
                webservice.Logout(user);
                log.Close();
            }
        }

        /// <summary>
        /// Pressing enter when using the txtSend.
        /// </summary>
        private void txtSend_KeyDown(object sender, KeyEventArgs e)
        {
            e.Handled = true;
            if (e.KeyCode == Keys.Enter)
            {
                if (txtSend.Text != "")
                {
                    webservice.SendMessage(user, txtSend.Text);
                    txtSend.Text = "";
                }
            }
        }

        /// <summary>
        /// The send Button implementation.
        /// </summary>
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (txtSend.Text != "")
            {
                webservice.SendMessage(user, txtSend.Text);
                txtSend.Text = "";
            }
        }

        /// <summary>
        /// Cancels any way of closing the Portal form.
        /// </summary>
        private void Portal_FormClosing_1(object sender, FormClosingEventArgs e)
        {
            if (!StartGame)
            {
                e.Cancel = true;
            }
        }

        /// <summary>
        /// The My Information Button implementation.
        /// </summary>
        private void btnMyInfo_Click(object sender, EventArgs e)
        {
            string[] temp = webservice.GetUserInfo(user);
            txtPlyr.Text = ("Player: " + temp[0]);
            txtWins.Text = ("Wins: " + temp[1]);
            txtLoss.Text = ("Losses: " + temp[2]);
            txtBlock.Text = ("Block Invites: ---");
        }

        /// <summary>
        /// The players list Click implementation.
        /// </summary>
        private void PlayerList_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                int temp = e.Y / 13;
                if (e.Y > (PlayerList.Items.Count * 13))
                {
                    PlayerList.SelectedIndex = -1;
                }
                else
                {
                    PlayerList.SelectedIndex = temp;
                }
                if (PlayerList.SelectedIndex >= 0)
                {
                    PlayerList.Select();
                    InvIndex = temp;
                    if (PlayerList.SelectedIndex >= 0)
                    {
                        string[] player = webservice.GetUserInfo(PlayerList.Items[PlayerList.SelectedIndex].ToString());
                        txtPlyr.Text = ("Username: " + player[0]);
                        txtWins.Text = ("Wins: " + player[1]);
                        txtLoss.Text = ("Losses: " + player[2]);
                        ChatMenu.Show(new Point(e.X + this.Location.X + PlayerList.Location.X, e.Y + this.Location.Y + PlayerList.Location.Y));
                    }
                }
            }
            if (e.Button == MouseButtons.Left)
            {               
                int temp = 0;
                if (e.Y > (PlayerList.Items.Count * 13))
                {
                    PlayerList.SelectedIndex = -1;
                }
                if (PlayerList.SelectedIndex > 0)
                {
                    temp = PlayerList.SelectedIndex;
                }
                if (PlayerList.Items.Count > 0)
                {
                    string[] player = webservice.GetUserInfo(PlayerList.Items[temp].ToString());
                    txtPlyr.Text = ("Username: " + player[0]);
                    txtWins.Text = ("Wins: " + player[1]);
                    txtLoss.Text = ("Losses: " + player[2]);
                    if (BlockList.Count > 0)
                    {
                        foreach (string S in BlockList)
                        {
                            if (player[0] == S)
                            {
                                txtBlock.Text = ("Block Invites: Yes");
                                break;
                            }
                            else
                            {
                                txtBlock.Text = ("Block Invites: No");
                            }
                        }
                    }
                    else
                    {
                        txtBlock.Text = ("Block Invites: No");
                    }
                    
                }
            }
        }

        /// <summary>
        /// Blocking specific player invite.
        /// </summary>
        private void BlockInviteChatMenu_Click(object sender, EventArgs e)
        {
            bool alreadyThere = false;
            string s = PlayerList.Items[InvIndex].ToString();
            foreach (string S in BlockList)
            {
                if (s == S)
                {
                    alreadyThere = true;
                }
            }
            if (alreadyThere == false)
            {
                BlockList.Add(s);
                txtBlock.Text = ("Block Invites: Yes");
            }
        }

        /// <summary>
        /// UnBlocking specific player invite.
        /// </summary>
        private void unblockInviteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string s = PlayerList.Items[InvIndex].ToString();
            foreach (string S in BlockList)
            {
                if (s == S)
                {
                    BlockList.Remove(s);
                    txtBlock.Text = ("Block Invites: No");
                    break;
                }
            }
        }

        /// <summary>
        /// The Randominvite Button implementation.
        /// </summary>
        private void btnRandInv_Click(object sender, EventArgs e)
        {
            if (inviting == false)
            {
                if (PlayerList.Items.Count > 0)
                {
                    int Index;
                    int found = PlayerList.Items.Count;
                    bool notFound = true;
                    while (notFound)
                    {
                        bool blocked = false;
                        Index = n.Next(PlayerList.Items.Count);
                        string s = PlayerList.Items[Index].ToString();
                        InvIndex = Index;

                        foreach (string S in BlockList)
                        {
                            if (s == S)
                            {
                                blocked = true;
                                break;
                            }
                        }
                        if (blocked == false)
                        {
                            notFound = false;
                            DialogResult dlgResult = MessageBox.Show("Would you like to play a game against " + s + " ?", "Continue?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                            if (dlgResult == DialogResult.Yes)
                            {
                                invitee = PlayerList.Items[InvIndex].ToString();
                                bool temp = webservice.SendInvite(user, s, 1);
                                if (temp == false)
                                {
                                    MessageBox.Show("This player is already trying to invite someone.", "Report");
                                    notFound = false;
                                }
                                else
                                {
                                    SizeG = 1;
                                    inviting = true;
                                }
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("You are already inviting someone.", "Report");
                }
            }
        }

        /// <summary>
        /// invites someone to a small game.
        /// </summary>
        private void smallToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (inviting == false)
            {
                invitee = PlayerList.Items[InvIndex].ToString();
                bool temp = webservice.SendInvite(user, invitee, 0);
                if (temp == false)
                {
                    MessageBox.Show("This player is already trying to invite someone.", "Report");
                }
                else
                {
                    SizeG = 0;
                    inviting = true;
                }
            }
            else
            {
                MessageBox.Show("You are already inviting someone.", "Report!");
            }
        }

        /// <summary>
        /// invites someone to a medium game.
        /// </summary>
        private void mediumToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (inviting == false)
            {
                invitee = PlayerList.Items[InvIndex].ToString();
                bool temp = webservice.SendInvite(user, invitee, 1);
                if (temp == false)
                {
                    MessageBox.Show("This player is already trying to invite someone.", "Report!");
                }
                else
                {
                    SizeG = 1;
                    inviting = true;
                }
            }
            else
            {
                MessageBox.Show("You are already inviting someone.", "Report!");
            }
        }

        /// <summary>
        /// invites someone to a big game.
        /// </summary>
        private void bigToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (inviting == false)
            {
                invitee = PlayerList.Items[InvIndex].ToString();
                bool temp = webservice.SendInvite(user, invitee, 2);
                if (temp == false)
                {
                    MessageBox.Show("This player is already trying to invite someone.", "Report!");
                }
                else
                {
                    SizeG = 2;
                    inviting = true;
                }
            }
            else
            {
                MessageBox.Show("You are already inviting someone.", "Report!");
            }
        }

        #endregion
    }
}
